package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1.校验手机号是否合法
        if (!RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            log.error("手机号格式错误！");
            return Result.fail("手机号格式错误!");
        }
        //2.生成验证码
        String code = createCode();
        //3.保存验证码到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.向用户手机发送验证码
        log.debug("发送验证码成功，验证码为：{}",code);
        //5.返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.校验手机号是否合法
        if (!RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            log.error("手机号格式错误！");
            return Result.fail("手机号格式错误!");
        }
        //2.获取用户输入验证码和session中的验证码
        String code = loginForm.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        //3.校验验证码是否正确
        if (redisCode == null || !redisCode.equals(code)) {
            // 3.如果不一致，返回错误信息
            log.error("验证码错误！");
            return Result.fail("验证码错误!");
        }
        //4.获取用户信息
        User user = lambdaQuery()
                .eq(User::getPhone, phone).
                one();
        //5.判断用户是否存在
        if (user == null) {
            //6.不存在，创建新用户
            user = createNewUser(phone);
        }
        //根据uuid生成token
        String token = UUID.randomUUID().toString(true);
        String tokenKey = LOGIN_USER_KEY + token;
        //7.保存用户信息到redis中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", userDTO.getId().toString());
        map.put("nickName", userDTO.getNickName());
        map.put("icon", userDTO.getIcon());
        stringRedisTemplate.opsForHash().putAll(tokenKey, map);
        log.debug("保存用户信息到redis中成功，用户信息为：{}",token);
        //模仿redis的session过期时间
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回前端token，到时候直接可以从请求头中获取token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取当前用户id
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.1截取年月
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(":yyyyMM");
        String nowStr = now.format(dateTimeFormatter);
        //3.拼接key
        String key = USER_SIGN_KEY + userId + nowStr;
        //4获取当前天是当前月中的第几天
        int dayOfMonth = now.getDayOfMonth()-1;
        //5.存入redis实现用户签到
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //1.获取当前用户id
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //2.1截取年月
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(":yyyyMM");
        String nowStr = now.format(dateTimeFormatter);
        //3.拼接key
        String key = USER_SIGN_KEY + userId + nowStr;
       //4获取当前天是当前月中的第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.获取本月截至今天的所有签到数据 BITFIELD key GET u 0
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if (result == null || result.isEmpty()) {
            //没有任何签到结果
            return Result.ok(0);
        }
        Long num = result.get(0);
        if (num == null || num == 0) {
            //没有任何签到结果
            return Result.ok(0);
        }
        //5.1定义一个计数器用于统计连续签到次数
        int count = 0;
        //5.循环遍历
        while(true){
            //5.2数据与1相与运算
            if ((num & 1) == 0) {
                //5.3若为0，则说明未签到，结束循环
                break;
            }
            //5.4若为1，则说明已签到，计数器加1
            count++;
            //5.5将数据右移一位
            num >>>= 1;
        }

        return Result.ok(count);
    }

    private User createNewUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        this.save(user);
        return user;
    }

    /**
     * 生成随机数验证码
     * */
    public static  String createCode() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}
